<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警示区域 -->
      <el-alert :closable="false" show-icon title="注意: 只允许为三级分类设置相关参数" type="warning"> </el-alert>
      <el-row class="row_cascader">
        <el-col>
          <span>选择商品分类: &nbsp;&nbsp;</span>
          <!-- 级联选择器区域 -->
          <el-cascader clearable v-model="selectKeys" :options="cateList" :props="cateProps" @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- tabs标签页 -->
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <!-- 动态参数面板 -->
            <el-tab-pane label="动态参数" name="many">
              <el-button type="primary" :disabled="disabled" @click="addDialogVisible = true">添加参数</el-button>
              <!-- 动态参数表格 -->
              <el-table :data="cateParmasMany" style="width: 100%" border scripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag type="primary" v-for="(item1, i) in scope.row.attr_vals" :key="i" closable @close="attrTagClose(scope.row, i)">{{ item1 }}</el-tag>
                    <!-- 添加参数的tag标签 -->
                    <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.addParamsName" ref="addParamsTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
                <el-table-column label="操作" width="300">
                  <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditeDialog(scope.row.attr_id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 静态属性面板 -->
            <el-tab-pane label="静态属性" name="only">
              <el-button type="primary" :disabled="disabled" @click="addDialogVisible = true">添加属性</el-button>
              <!-- 静态属性表格 -->
              <el-table :data="cateParmasOnly" style="width: 100%" border scripe>
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag type="primary" v-for="(item1, i) in scope.row.attr_vals" :key="i" closable @close="attrTagClose(scope.row, i)">{{ item1 }}</el-tag>
                    <!-- 添加参数的tag标签 -->
                    <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.addParamsName" ref="addParamsTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
                <el-table-column label="操作" width="300">
                  <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditeDialog(scope.row.attr_id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="paramsText" :visible.sync="addDialogVisible" width="50%" @close="clearDialog('addRuleFormRef')">
      <el-form :model="addRuleForm" :rules="addRuleFormRules" ref="addRuleFormRef" label-width="100px">
        <el-form-item :label="paramsText + '名'" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addcatePerams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="paramsText" :visible.sync="editDialogVisible" width="50%" @close="clearDialog('editRuleFormRef')">
      <el-form :model="editRuleForm" :rules="editRuleFormRules" ref="editRuleFormRef" label-width="100px">
        <el-form-item :label="paramsText + '名'" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editcatePerams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import commonAPI from '@/api/commonAPI/commonAPI.js'
import { clearDialog } from '@/mixin.js'
export default {
  data() {
    return {
      // 所有商品分类数据
      cateList: [],
      // 级联选择器绑定的商品分类信息(必须是数组)
      selectKeys: [1, 4, 24], // 默认选择立柜空调
      // 级联选择器的配置对象
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // activeName tabs标签页绑定的用来选择当前选中的是哪一项
      activeName: 'many',
      // 控制按钮是否禁用
      disabled: true,
      // 分类参数列表(动态参数)
      cateParmasMany: [],
      // 静态参数
      cateParmasOnly: [],
      // 控制添加参数和属性的对话框是否打开
      addDialogVisible: false,
      // 控制编辑参数和属性的对话框是否打开
      editDialogVisible: false,
      // 要修改的分类参数对象
      currentEditObj: {},
      // 添加表单数据对象
      addRuleForm: {
        attr_name: ''
      },
      // 修改表单数据对象
      editRuleForm: {
        attr_name: ''
      },
      // 添加表单校验对象
      addRuleFormRules: {
        attr_name: { required: true, message: '请输入参数名称', trigger: 'blur' }
      },
      // 修改表单校验对象
      editRuleFormRules: {
        attr_name: { required: true, message: '请输入参数名称', trigger: 'blur' }
      }
    }
  },
  mixins: [clearDialog],
  created() {
    this.getcate()
    this.getParams()
  },
  watch: {
    selectKeys: {
      handler(newVal) {
        this.disabled = newVal.length !== 3
      },
      immediate: true
    }
  },
  computed: {
    // 分类id
    cateId() {
      // 该api数据只能接收到三级分类的数据
      if (this.selectKeys.length === 3) {
        return this.selectKeys[this.selectKeys.length - 1]
      }
      return null
    },
    // 动态渲染添加对话框的标题(添加动态参数与添加静态属性的对话框是同一个)
    paramsText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    async getcate() {
      // 请求所有的商品分类数据
      const { data: res } = await commonAPI({ method: 'get', url: 'categories' })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败')
      this.$message.success('获取商品分类数据成功')
      this.cateList = res.data
    },
    // 级联选择器选项改变时触发
    handleChange() {
      this.getParams()
    },
    handleClick(tab, event) {
      console.log(tab, event)
      this.getParams()
    },
    async getParams() {
      /* vue 监听会在该函数的后面触发,而计算属性立马触发,在该函数之前 */
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.cateParmasMany = []
        this.cateParmasOnly = []
        return
      }
      const { data: res } = await commonAPI({ method: 'get', url: `categories/${this.cateId}/attributes`, params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('请求分类参数失败!')
      this.$message.success('请求分类参数成功!')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制是显示文本框还是按钮(默认显示按钮)(给每一行添加单独的防止共用)
        item.inputVisible = false
        // 当时输入框时,双向绑定的要添加的参数名
        item.addParamsName = ''
      })
      if (this.activeName === 'many') {
        // 动态参数
        this.cateParmasMany = res.data
      } else {
        // 静态属性
        this.cateParmasOnly = res.data
      }
      // console.log(res)
    },
    // 添加确定提交时触发
    addcatePerams() {
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await commonAPI({ method: 'post', url: `categories/${this.cateId}/attributes`, params: { attr_name: this.addRuleForm.attr_name, attr_sel: this.activeName } })
        if (res.meta.status !== 201) return this.$message.error(`添加${this.paramsText}失败!`)
        this.$message.success(`添加${this.paramsText}成功!`)
        this.getParams()
        this.addDialogVisible = false
      })
    },
    // 打开编辑对话框时触发
    async showEditeDialog(id) {
      const { data: res } = await commonAPI({ method: 'get', url: `categories/${this.cateId}/attributes/${id}`, params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('查询分类参数失败!')
      this.$message.success('查询分类参数成功!')
      this.editRuleForm.attr_name = res.data.attr_name
      this.currentEditObj = res.data
      this.editDialogVisible = true
    },
    // 编辑确定提交时触发
    editcatePerams() {
      this.$refs.editRuleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await commonAPI({ method: 'put', url: `categories/${this.currentEditObj.cat_id}/attributes/${this.currentEditObj.attr_id}`, params: { attr_name: this.editRuleForm.attr_name, attr_sel: this.activeName } })
        if (res.meta.status !== 200) return this.$message.error('编辑分类参数失败!')
        this.$message.success('编辑分类参数成功!')
        this.getParams()
        this.editDialogVisible = false
      })
    },
    // 删除功能函数
    async deleteParams(id) {
      const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      this.$message({ type: 'success', message: '删除成功!' })
      const { data: res } = await commonAPI({ method: 'delete', url: `categories/${this.cateId}/attributes/${id}` })
      if (res.meta.status !== 200) return this.$message.error('删除参数失败!')
      this.$message.success('删除参数成功!')
      this.getParams()
    },
    // 当是文本框时按回车键触发
    // 当时文本框时且失去焦点时触发
    handleInputConfirm(row) {
      if (row.addParamsName.trim().length === 0) {
        row.addParamsName = ''
        row.inputVisible = false
        return
      }
      // 如果不为空,则执行以下操作
      row.attr_vals.push(row.addParamsName)
      row.addParamsName = ''
      row.inputVisible = false
      // 保存到数据库
      this.setAttr(row)
    },
    // 把添加或修改的参数保存到数据库中
    setAttr(row) {
      commonAPI({
        method: 'put',
        url: `categories/${this.cateId}/attributes/${row.attr_id}`,
        params: {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      })
        .then(_ => {
          this.$message.success('添加参数成功!')
        })
        .catch(_ => {
          this.$message.error('添加参数失败!')
        })
    },
    // 当时按钮时点击触发
    showInput(row) {
      row.inputVisible = true
      // $nextTick: 当页面的DOM元素被重新渲染后才会执行该方法类的回调
      this.$nextTick(_ => {
        // console.log(this.$refs.addParamsTagInputRef) // 是 一个实例对象
        this.$refs.addParamsTagInputRef.$refs.input.focus()
      })
    },
    // 当tag标签关闭时触发
    attrTagClose(row, i) {
      row.attr_vals.splice(i, 1)
      this.setAttr(row)
    }
  }
}
</script>

<style lang="less" scoped>
.row_cascader {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
